package cn.tedu.ivos.audit.service.impl;

import cn.tedu.ivos.application.mapper.ApplicationMapper;
import cn.tedu.ivos.application.pojo.entity.Application;
import cn.tedu.ivos.audit.mapper.AuditMapper;
import cn.tedu.ivos.audit.pojo.dto.AuditQuery;
import cn.tedu.ivos.audit.pojo.dto.AuditSaveParam;
import cn.tedu.ivos.audit.pojo.entity.Audit;
import cn.tedu.ivos.audit.pojo.vo.AuditVO;
import cn.tedu.ivos.audit.service.AuditService;
import cn.tedu.ivos.base.enums.ApplicationStatusEnum;
import cn.tedu.ivos.base.enums.AuditStatusEnum;
import cn.tedu.ivos.user.mapper.UserMapper;
import cn.tedu.ivos.user.pojo.vo.UserVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.StringJoiner;

@Service
@Transactional
@Slf4j
public class AuditServiceImpl implements AuditService {
    @Autowired
    AuditMapper auditMapper;
    @Autowired
    UserMapper userMapper;
    @Autowired
    ApplicationMapper applicationMapper;

    @Override
    public void insertAudit(Application application) {
        log.debug("为当前申请单生成对应的审批单数据业务:参数{}",application);
        //1.获取审批人id集合[106,103]
        List<Long> userIdList = application.getAuditUserIdList();
        System.out.println(userIdList);
        //2.遍历集合，有几个审批人就生成几条审批数据
        for (int i = 0;i < userIdList.size();i++){
            Audit audit = new Audit();
            //3.设置申请单id,也就是批哪个申请表
            audit.setApplicationId(application.getId());
            //设置审批人id
            audit.setAuditUserId(userIdList.get(i));
            //5.设置当前审批数据的次序
            audit.setAuditSort(i);
            //设置当前审批数据的状态
            if (i==0){
                audit.setAuditStatus(AuditStatusEnum.MY_PENDING.getCode());
            }else {
                audit.setAuditStatus(AuditStatusEnum.PENDING.getCode());
            }
            //7.设置新增时间
            audit.setCreateTime(new Date());
            log.debug("参数{}",audit);
            //8.审批数据入库
            auditMapper.insert(audit);
        }
    }

    @Override
    public List<AuditVO> selectAuditByApplicationId(Long id) {
        log.debug("申请id，参数{}",id);
        List<AuditVO> auditVOList = auditMapper.selectByApplicationId(id);
        return auditVOList;
    }

    @Override
    public void delect(Long id) {
        auditMapper.delect(id);
    }

    @Override
    public List<AuditVO> selectAudit(AuditQuery auditQuery) {
        log.debug("查询审批数据业务:参数={}",auditQuery);
        List<AuditVO> list = auditMapper.selectAudit(auditQuery);
        //遍历每一个审批对象,依次为每个审批对象补充审批人数据
        for (int i = 0;i < list.size();i++){
            AuditVO auditVO = list.get(i);
            //处理当前遍历到的审批对象,给他补充审批人数据
            assignAuditUserList(auditVO);
        }
        return list;
    }

    private void assignAuditUserList(AuditVO auditVO) {
        List<String> auditUsernameList = new ArrayList<>();
        List<Long> auditUserIdList = new ArrayList<>();
        //根据审批单VO中的申请单id，查询当前审批单对应的申请单下所有的审批单数据
        List<AuditVO> auditVOList = auditMapper.selectByApplicationId(auditVO.getApplicationId());
        //依次遍历每一个审批单,获取当前审批单中的审批人id与姓名
        for (int i = 0;i < auditVOList.size();i++){
            Long userId = auditVOList.get(i).getAuditUserId();
            auditUserIdList.add(userId);
            UserVO user = userMapper.selectById(userId);
            auditUsernameList.add(user.getUsername());
        }
        StringJoiner stringJoiner = new StringJoiner(",");
        for (String username : auditUsernameList){
            stringJoiner.add(username);
        }
        auditVO.setAuditUsernameList(stringJoiner.toString());
        auditVO.setAuditUserIdList(auditUserIdList);
    }

    @Override
    public void updateAudit(AuditSaveParam auditSaveParam) {
        log.debug("更新审批数据业务:参数{}",auditSaveParam);
        Audit audit = new Audit();
        BeanUtils.copyProperties(auditSaveParam,audit);
        audit.setUpdateTime(new Date());
        //准备当前审批对应的申请单对象
        Application application = new Application();
        application.setId(audit.getApplicationId());
        application.setUpdateTime(new Date());
        //需要判断当前要做通过处理还是驳回处理
        if (audit.getAuditStatus().equals(AuditStatusEnum.AUDITED.getCode())){//审批通过
            //更新当前的审批单
            auditMapper.update(audit);
            /* 继续查是否有其他的审批单:其他审批单与当前对应的申请单是同一个*/
            AuditQuery auditQuery = new AuditQuery();
            auditQuery.setApplicationId(audit.getApplicationId());
            //根据申请单id查询当前申请单对应的所有未审批单总数,注意：当前审批单已审批通过!
            Integer count = auditMapper.selectRestAuditCount(auditQuery);
            log.debug("还有多少审核单,参数{}",count);
            if (count>0){
                //下一条审批数据是当前审批数据的次序+1
                auditQuery.setAuditSort(audit.getAuditSort()+1);
                //根据申请单id与审批次序,查出当前审批单之后的下一条审批单
                List<AuditVO> auditVOList = auditMapper.selectAudit(auditQuery);
                if (auditVOList!=null && auditVOList.size()>0){
                    AuditVO auditVO = auditVOList.get(0);
                    //创建一个空对象,代表第二个审批单对象
                    Audit audit2 = new Audit();
                    audit2.setId(auditVO.getId());//这个审批单就是刚查出来的第二条审批
                    //设置第二条审批单的状态为"待我审核",并更新
                    audit2.setAuditStatus(AuditStatusEnum.MY_PENDING.getCode());
                    auditMapper.update(audit2);
                }
                //设置申请单的状态为“审核中”
                application.setStatus(ApplicationStatusEnum.AUDIT.getCode());
                applicationMapper.update(application);
            }else {
                application.setStatus(ApplicationStatusEnum.AUDITED.getCode());
                applicationMapper.update(application);
            }

        }else {//审批驳回
            //更新当前的审批单
            auditMapper.update(audit);
            /* 继续查是否有其他的审批单:其他审批单与当前对应的申请单是同一个*/
            AuditQuery auditQuery = new AuditQuery();
            auditQuery.setApplicationId(audit.getApplicationId());
            List<AuditVO> auditVOList = auditMapper.selectAudit(auditQuery);
            if (auditVOList!=null && auditVOList.size()>0){
                for (int i = 0;i < auditVOList.size();i++){
                    AuditVO auditVO = auditVOList.get(i);
                    if (AuditStatusEnum.PENDING.getCode().equals(auditVO.getAuditStatus())){
                        auditMapper.delectById(auditVO.getId());
                    }
                }
            }
            //设置申请单的状态为“审核中”
            application.setStatus(ApplicationStatusEnum.REJECT.getCode());
            application.setRejectReason(auditSaveParam.getRejectReason());
            applicationMapper.update(application);
        }
    }
}
